//
//  CGQduankouListViewController.swift
//  SheYangBigData
//
//  Created by 叁拾叁 on 2021/4/7.
//  Copyright © 2021 叁拾叁. All rights reserved.
//


import UIKit
import MJRefresh
import RxSwift
import RxDataSources
import Then
import SDCycleScrollView

class CGQduankouListViewController: SYBaseTableViewController {
    
    fileprivate var vm: VGTableViewPageViewModel<NSPortguanliRecordsModel>!
    
    var searchView: CGQSearchView!
    var params: [String: String]?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setTableView()
        setNoDataView()
        setupViewModel()
        self.title = "端口列表"
        setSearchView()
    }
    
    
    
    @objc func rightAction() {
        
    }
    
    
    fileprivate func setupViewModel() {
        vm = VGTableViewPageViewModel<NSPortguanliRecordsModel>()
        vm.tableView = tableView
        vm.emptyViewParams = ("", "", 40.0, 30.0)
        tableView.vg_pageProtocol = vm
        vm.getList(type: .duankouList(dic: self.params ?? [:], page: vm.vg_pageNo, size:vm.size), dispose: dispose)
        vm.getDataClosure = {[weak self] page in
            if let `self` = self {
                self.vm.getList(type: .duankouList(dic: self.params ?? [:],page: self.vm.vg_pageNo, size:self.vm.size), dispose: self.dispose)
            }
        }
        vm.loadDataClosure = {[weak self] success in
            if let `self` = self {
                if success {
                    self.loadDataSuccessed()
                }
            }
        }
    }
    
    
    
    func loadDataSuccessed() {
        DispatchQueue.main.async {
            
            self.setDataSource()
        }
    }
    
    func setTableView() {
        
        //创建表格视图
        self.tableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT-BOTTOM_SAFE_HEIGHT), style:.plain)
        self.tableView.separatorStyle = .none
        self.tableView.backgroundColor = Constant.bgViewColor
        self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        self.view.addSubview(self.tableView!)
        
        tableView.rx.itemSelected
            .subscribe(onNext:{ [weak self] indexPath in
                if let `self` = self {
                    
                    let m:[NSPortguanliRecordsModel] = self.vm.dataSource
                    let vc = CGQduankouClassViewController(id: m[indexPath.row].portNumber ?? "",model: m[indexPath.row])
                    self.sy_push(vc)
                }
            })
            .disposed(by:dispose)
    }
    
    func setNoDataView() {
        noDataView = SYNoDataView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-NAV_HEIGHT))
        noDataView.isHidden = true
        tableView.addSubview(noDataView)
    }
    func setDataSource() {
        
        //初始化数据
        let sections = Observable.just([
            NSPortguanliRecordsModelSection(header: "", items: self.vm.dataSource)//self.vm.dataSource)
        ])
        
        //创建数据源
        let dataSource = RxTableViewSectionedAnimatedDataSource<NSPortguanliRecordsModelSection>(
            //设置单元格
            configureCell: { ds, tv, ip, item in
                
                let cell: CGQduankouCell = tv.dequeueReusableCell(withIdentifier: "Cell")
                    as? CGQduankouCell ?? CGQduankouCell(style: .default, reuseIdentifier: "Cell")
                    cell.configureView(model: item)
                cell.selectionStyle = .none
                cell.currentVC = self 
                cell.passParamsClosure = {[weak self] v in
                    if let `self` = self {
                        
                        self.requestVM.baseRequest(disposeBag: self.dispose, type: .duankoukaiguan(dic: ["portNumber" : item.portNumber ?? "", "portStatus":  "\(v)" ]), modelClass: SGBaseModel<CGQshouyeModel>.self) {[weak self] (res) in
                            if let `self` = self  {
                                
                                
                                self.sy_toast(res.message ?? "")
                                self.setupViewModel()
                            }
                            
                        } Error: {
                            
                        }
                    }
                    
                }
                return cell
                
            },
            //设置分区头标题
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            })
        tableView.dataSource = nil
        //绑定单元格数据
        sections
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: dispose)
        
    }
    
    
    func setSearchView() {
        searchView = CGQSearchView(frame: CGRect.init(x: 0, y: STATUSBAR_HEIGHT + 10, width: SCREEN_WIDTH, height: 38.0.autoWidth()))
        searchView.tf.placeholder = "搜索"
        searchView.clickChoiceClosure = {[weak self] index in
            if let `self` = self {
                if index == 0 {
                    self.popVC()
                } else {
                                        self.params = ["portName":self.searchView.tf.text ?? ""]
                    self.setupViewModel()
                }
                //
            }
        }
        searchView.tixianBt.addAction {[weak self] in
            if let `self` = self {
                
            }
        }
        
        view.addSubview(searchView)
        
    }
}


//自定义Section
struct NSPortguanliRecordsModelSection {
    var header: String
    var items: [Item]
}

extension NSPortguanliRecordsModelSection : AnimatableSectionModelType {
    typealias Item = NSPortguanliRecordsModel

    var identity: String {
        return header
    }

    init(original: NSPortguanliRecordsModelSection, items: [Item]) {
        self = original
        self.items = items
    }
}

extension NSPortguanliRecordsModel: IdentifiableType {
    var identity: String {
        return id!
    }

    typealias Identity = String
}

